package com.atom.common.remote.user;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atom.common.CommonConstant;
import com.atom.common.exception.AvensRemoteDatabaseDaoException;
import com.atom.common.util.CharSetUtil;
import com.atom.common.util.GlobalConfigReader;
import com.atom.common.util.HttpUtil;
import com.atom.common.util.JsonResultParser;
import com.atom.common.util.TicketUtil;
@Service
public class RemoteUserDao {
  
  private static Logger logger = Logger.getLogger(RemoteUserDao.class);

  @Autowired(required = false) HttpSession session;

  private static final String USER_HOST = GlobalConfigReader.getStringValue(CommonConstant.GGUSER_SERVERNAME);
  private static final String AUTH_HOST = GlobalConfigReader.getStringValue(CommonConstant.AUTHORITY_SERVERNAME);
  
  /**
   * Description: 获取机构树 
   * @return
   */
  public String getOrgTree() {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "org.newtree.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);    
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return result;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("GET OrgTree Failed");
    }
  }

  /**
   * Description: 根据机构查看直属人员（主职）
   * @param orgid
   * @return
   */
  public String listUserByOrgid(String orgid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.listMainUserByOrgid.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("orgid", orgid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return result;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("LIST USER BY ORGID Failed");
    }
  }

  /**
   * Description: 获取所有用户的基本信息 
   * @return
   */
  public String getAllUsers() {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.getAllUsers.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);    
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("GET OrgTree Failed");
    }
  }

  /**
   * Description: 获取所有机构信息 
   * @return
   */
  public String getAllOrgs() {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "org.getAllOrgs.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);    
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("GET OrgTree Failed");
    }
  }
  
  /**
   * Description: 根据机构id获取自身和下属机构信息 
   * @return
   */
  public String listOrgByOrgid(String orgid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "org.listOrgByOrgid.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);    
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("orgid", orgid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("listOrgByOrgid Failed");
    }
  }

  /**
   * Description: 判断用户是否为某部门某职位
   * @param userid
   * @param orgid
   * @param pos 
   * kezhang=队长，副队长，科长，副科长，组长，副组长，所长，副所长，秘书
   * zhengkezhang=队长，科长，组长，所长
   * fukezhang=副队长，副科长，副组长，副所长，秘书

   * chuzhang=主任，副主任，处长，副处长，馆长，副馆长，社长，副社长，总编辑，副总编辑，总工程师
   * zhengchuzhang=主任，处长，馆长，社长，总编辑，总工程师
   * fuchuzhang=副主任，副处长，副馆长，副社长，副总编辑

   * buzhang=部长，副部长
   * zhengbuzhang=部长
   * fubuzhang=副部长
   * @return true/false
   */
  public boolean checkUserByOrgidAndPos(String userid, String orgid, String pos) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.checkUserByOrgidAndPos.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("userid", userid);
      params.put("orgid", orgid);
      params.put("pos", pos);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result).equals("1") ? true : false;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("Check User By Orgid And Pos Failed");
    }
  }

  /**
   * Description: 获取机构全称
   * @param orgid
   * @return "安全部-保卫处"
   */
  public String getFullOrgname(String orgid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "org.getOrgname.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("orgid", orgid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      JSONObject json = new JSONObject(result);
      return json.getString("orgname");
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("Get Full Orgname Failed");
    }
  }

  /**
   * Description: 获取用户所在部门某职位的人
   * @param userid
   * @param pos
   * @param level 0:正部长 1:副部长
   * @return
   * [
   *        {
   *            "userid": "620822198601139790",
   *            "username": "白蓝宇"
   *        }
   * ]
   */
  public String listUserByOrgidAndPosAndLev(String userid, String pos, String level) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.listUserByOrgidAndPosAndLev.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("userid", userid);
      params.put("pos", pos);
      params.put("level", level);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("List User By Orgid And Pos And Lev Failed");
    }
  }

  /**
   * Description: 获取院领导
   * @return
   * [
   *         {
   *             "userid": "120104196812286813",
   *             "username": "冯乃恩"
   *         }
   * ]
   */
  public String getLeader() {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.getLeader.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("Get Leader Failed");
    }
  }

  /**
   * Description: 根据职位和级别获取用户信息
   * @param orgid
   * @param pos
   * @return
   */
  public String listUserByOrgidAndPos(String orgid, String pos) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.listUserByOrgidAndPos.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("orgid", orgid);
      params.put("pos", pos);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("List User By Orgid And Pos Failed");
    }
  }

  /**
   * Description: 查询机构信息
   * @param fld
   * @param value
   * @return
   */
  public String queryOrgInfo(String fld, String value) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "org.queryOrgInfo.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("fld", fld);
      params.put("value", value);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("QUERY ORG INFO Failed");
    }
  }

  /**
   * Description: 查询用户信息
   * @param fld
   * @param value
   * @return
   */
  public String queryUserInfo(String fld, String value) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.queryUserInfo.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("fld", fld);
      params.put("value", value);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("QUERY USER INFO Failed");
    }
  }
  
  /**
   * Description: 根据角色查询用户
   * @param roleid
   * @return
   */
  public String listRoleUser(String roleid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "userrole.getUserByRole.do";
    StringBuffer url = new StringBuffer(AUTH_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("roleid", roleid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("List Role User Failed");
    }
  }
  
  /**
   * Description: 根据机构和职位查询用户列表
   * @param orgid
   * @param positions
   * @return
   */
  public String oaQuery(String orgid, String positions) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.oaQuery.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("orgid", orgid);
      params.put("positions", positions);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("User Query Failed");
    }
  }
  
  public String getUserByApAndOrgid(String actualpositionid, String orgid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.getUserByApAndOrgid.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("actualpositionid", actualpositionid);
      params.put("orgid", orgid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("User Query Failed");
    }
  }
  
  public String getUserByRoleidAndOrgid(String roleid, String orgid) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.getUserByRoleidAndOrgid.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("roleid", roleid);
      params.put("orgid", orgid);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return JsonResultParser.getData(result);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("User Query Failed");
    }
  }
  
  public String verifyUseridAndPwd(String userid, String password) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "user.verifyUseridAndPwd.do";
    StringBuffer url = new StringBuffer(USER_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("userid", userid);
      params.put("password", password);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return result;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("verifyUseridAndPwd Failed");
    }
  }

  public String getUserByRole(String roleId) {
    Map<String, String> params = new HashMap<String, String>();
    final String METHOD = "userrole.getUserByRole.do";
    StringBuffer url = new StringBuffer(AUTH_HOST);
    url.append(METHOD);   
    try {
      String finalUrl = TicketUtil.appendTicket(url, session);
      params.put("roleId", roleId);
      String result = CharSetUtil.decodeUnicode(HttpUtil.get(finalUrl, params));
      return result;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensRemoteDatabaseDaoException("getUserByRole Failed");
    }
  }
  
}